package boltdb

import (
	"log"
	"github.com/boltdb/bolt"
	"errors"

)

/**
 * Created by train on 16/12/27.
 */


const (
	BUCKET_MATCHS     = "BUCKET_MATCHS"
)
func initBuntdb(name string)*bolt.DB{

	db,err:= bolt.Open("data/"+name+".db", 0600, nil)

	if err!=nil{
		log.Fatal(err)
	}

	return db
}
func CheckBucket(name string,bucket string) error{
	db:=initBuntdb(name)
	defer db.Close()

	return db.View(func(tx *bolt.Tx) error {
		if tx.Bucket([]byte(bucket))!=nil{
			return nil
		}
		return errors.New("not found")
	})
}
func Put(name string,bucket string,key string,value string) error{
	db:=initBuntdb(name)
	defer db.Close()
	return db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucketIfNotExists([]byte(bucket))
		if err != nil {
			return err
		}
		b := tx.Bucket([]byte(bucket))

		return b.Put([]byte(key), []byte(value))
	})
}
func BatchPut(name string,bucket string,data []map[string]string) error{

	db:=initBuntdb(name)
	defer db.Close()
	return db.Batch(func(tx *bolt.Tx) error {

		_, err := tx.CreateBucketIfNotExists([]byte(bucket))

		if err != nil {

			return err
		}
		b := tx.Bucket([]byte(bucket))
		for _,v:=range data{
			for key,val:=range v{
				b.Put([]byte(key), []byte(val))
			}
		}
		return nil
	})

}
func BatchPutMap(name string,bucket string,data map[string]string) error{

	db:=initBuntdb(name)
	defer db.Close()
	return db.Batch(func(tx *bolt.Tx) error {

		_, err := tx.CreateBucketIfNotExists([]byte(bucket))

		if err != nil {

			return err
		}
		b := tx.Bucket([]byte(bucket))
		for key,val:=range data{
			b.Put([]byte(key), []byte(val))
		}
		return nil
	})

}
func Get(name string,bucket string,key string,fn func(string)) {
	db:=initBuntdb(name)
	defer db.Close()
	db.View(func(tx *bolt.Tx) error {

		b := tx.Bucket([]byte(bucket))
		if b==nil{
			fn("")
		}else{
			v := b.Get([]byte(key))
			fn(string(v))
		}

		return nil
	})
}
func ScanTx(name string,fn func(tx *bolt.Tx))  {
	db:=initBuntdb(name)
	defer db.Close()
	db.View(func(tx *bolt.Tx) error {
		fn(tx)

		return nil
	})
}
func Scan(name string,bucket string,fn func(bucket *bolt.Bucket))  {
	db:=initBuntdb(name)
	defer db.Close()

	db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte(bucket))

		fn(b)

		return nil
	})
}